package utils

import (
	"fmt"
	"time"

	"github.com/dgrijalva/jwt-go"
)

type loginUtil struct {
}

type LoginUser struct {
	Id int
	// 状态，0：未授权，1：已授权
	Status     int
	SessionKey string
	CreateTime int64 // token 创建时间
	Extra      interface{}
}

var LoginUtil = &loginUtil{}

func (this *loginUtil) NeedRefreshToken(loginUser *LoginUser) bool {
	if loginUser.CreateTime <= time.Now().Add(-JwtUtil.GetJwtConfig().JwtDueTime*time.Hour/2).Unix() {
		// 过了一半时间了，更新token
		return true
	}
	return false
}

func (this *loginUtil) GetLoginUserId(token string) (userId int, err error) {
	var loginUser *LoginUser
	loginUser, err = this.GetLoginUser(token)
	if err != nil {
		return
	}
	userId = loginUser.Id
	return
}

func (this *loginUtil) GetLoginUser(token string) (loginUser *LoginUser, err error) {
	var claims jwt.MapClaims
	claims, err = JwtUtil.ParseTokenWithMapClaims(token)
	if err == nil {
		loginUser = &LoginUser{}
		loginUser.Id, err = ParseInt(claims["id"])
		if err != nil {
			return
		}
		loginUser.SessionKey = fmt.Sprintf("%v", claims["sk"])
		loginUser.Status = ParseIntOrDefault(claims["st"], 0)
		loginUser.CreateTime = ParseInt64OrDefault(claims["iat"], 0)
		loginUser.Extra = claims["ex"]
	}
	return
}

func (this *loginUtil) GenerateToken(user *LoginUser) (string, error) {
	claims := make(jwt.MapClaims)
	claims["id"] = user.Id
	claims["sk"] = user.SessionKey
	claims["st"] = user.Status
	claims["ex"] = user.Extra
	return JwtUtil.GenerateTokenWithMapClaims(claims)
}
